package com.atguigu.spzx.cloud.gateway.security.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * projectName: com.atguigu.spzx.cloud.gateway.security.filter
 * @author: 魏嘉禄
 * description:
 * time: 2025/6/25 20:23
 */
@Component
//实现这两个接口，就可以实现全局过滤器
//GlobalFilter：全局过滤器
//Ordered：过滤器的优先级
public class AuthorizationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//过滤器的具体逻辑
////        String username = exchange.getRequest().getQueryParams().getFirst("username");//获取请求参数
////        if (!StringUtils.hasText(username)){//判断请求参数是否为空
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//设置响应状态码
//            return exchange.getResponse().setComplete();//返回响应
//        }
//        return chain.filter(exchange);//继续执行下一个过滤器
        // 1. 检查atguigu请求头
        String authHeader = exchange.getRequest().getHeaders().getFirst("Truth");
        if (!"atguigu".equals(authHeader)) {
            System.out.println("认证失败：缺少或错误的atguigu请求头");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
